#include <QDebug>
#include "ConfigManager.h"

ConfigManager::ConfigManager(QString configPath,
                             QObject *parent) :
   QObject(parent),
   theConfiguration(configPath, QSettings::IniFormat)
{
   if(!theConfiguration.isWritable())
   {
      qCritical() << "Configuration file" << theConfiguration.fileName() << "is read-only";
   }
}

void ConfigManager::slotRegisterPlugin(Plugin *plugin)
{
   connect(plugin, SIGNAL(signalGetConfigValue(QString,QVariant&)),
           this, SLOT(slotGetConfigValue(QString,QVariant&)),
           Qt::BlockingQueuedConnection);
   connect(plugin, SIGNAL(signalSetConfigValue(QString,QVariant&)),
           this, SLOT(slotSetConfigValue(QString,QVariant&)));
   connect(this, SIGNAL(signalConfigUpdate(QString,QVariant&)),
           plugin, SLOT(slotConfigUpdate(QString,QVariant&)));
}

void ConfigManager::slotGetConfigValue(const QString &key,
                                       QVariant &value)
{
   if(theConfiguration.contains(key))
   {
      value = theConfiguration.value(key);
   }
   else
   {
      qCritical() << "Failed to retrieve configuration key:" << key;
   }
}

void ConfigManager::slotSetConfigValue(const QString &key,
                                       QVariant &value)
{
   theConfiguration.setValue(key, value);
   emit signalConfigUpdate(key, value);
}
